// @flow
import React, { Component } from 'react'
import { Modal, message } from 'antd'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
type Props = {
  visible: boolean,
  closeModal: Function,
  refreshPoint: Function,
  getVarData: Function,
  deviceId?: string,
  kmxData: Array<Object>
}
type States = {
  loading: boolean
}

class SyncKMX extends Component {
  props: Props
  state: States
  syncKMX: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      loading: false
    }
    this.syncKMX = this.syncKMX.bind(this)
  }

  syncKMX () {
    const { closeModal, kmxData } = this.props
    this.setState({
      loading: true
    })
    kmxData.map((d, i) => {
      universalFetch(`${__SERVICE_API__}device/kmx/meta2kmx?point_id=${d.id}`)
        .then(res => res.json())
        .then((json) => {
          if (json.code !== 200000) {
            throw new Error(JSON.stringify({ code: json.code, message: json.message }))
          }
          this.setState({
            loading: false
          })
          closeModal()
          message.success('同步选中设置成功')
          this.props.refreshPoint()
          this.props.getVarData()
        })
        .catch((error) => {
          handleFetchError(error)
          console.error(error)
          this.setState({
            loading: false
          })
          message.error('同步选中设置失败: ' + error.message)
        })
    })
  }
  render () {
    const { visible, closeModal } = this.props
    const { loading } = this.state
    return (
      <Modal title='同步选中设置'
        visible={visible}
        onCancel={closeModal}
        confirmLoading={loading}
        maskClosable={false}
        onOk={this.syncKMX}
        >
        <div>
          <p>确定要同步选中设置吗？</p>
        </div>
      </Modal>
    )
  }
}

export default SyncKMX
